package util

import (
	"fmt"
	"io"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

var logConfig string
var logAdapterName string
var log *logs.BeeLogger
var adapter *BeeLoggerAdapter

type BeeLoggerAdapter struct {
	*logs.BeeLogger
}

type LogEntry interface {
	Format() string
	Level() int
}

func (bla *BeeLoggerAdapter) Write(p []byte) (int, error) {
	bla.Debug(string(p))
	return 0, nil
}

func InitLogger(runmode string) {
	log = logs.NewLogger(1000)
	if runmode == "dev" {
		logAdapterName = "console"
		logConfig = `{"level":7, "color":true}`
		log.SetLevel(logs.LevelDebug)
	} else if runmode == "test" || runmode == "uat" {
		logAdapterName = "file"
		logConfig = fmt.Sprintf(`{"filename":"%s"}`, beego.AppConfig.String("logFile"))
		log.SetLevel(logs.LevelDebug)
	} else {
		log.SetLevel(logs.LevelInfo)
	}
	adapter = &BeeLoggerAdapter{log}
	log.SetLogger(logAdapterName, logConfig)
}

func GetLoggerProfile() (string, string) {
	return logAdapterName, logConfig
}

func UseBeeLogger() io.Writer {
	return adapter
}

func WriteLog(entry LogEntry) {
	format := entry.Format()
	if entry.Level() == logs.LevelError {
		log.Error(format)
	} else {
		log.Debug(format)
	}
}
